require(['bbcare'], function($bb) {
    var URL = $bb.baseUrl("followup");

    var vm = new Vue({
        el: '.wrapper',
        data: function() {
            var that = this
            return {
                step: {
                    index: 1,
                    group: [ '选择导出内容', '导出文件类型', '导出完成' ]
                },
                queue: '',
                queueList: [],
                date: [],
                dateCopy: [],
                kinds: {
                    active: 1,
                    list: [
                        { id: 1, label: 'Excel' },
                    ]
                },
                nodeList: [
                    { label: '建档', id: 1 },
                    { label: '一月龄', id: 1 },
                    { label: '二月龄', id: 1 },
                    { label: '三月龄', id: 1 },
                    { label: '四月龄', id: 1 },
                ],
                nodes: [],
                contentList: [
                    { label: '建档', id: 1 },
                    { label: '一月龄', id: 1 },
                    { label: '二月龄', id: 1 },
                    { label: '三月龄', id: 1 },
                    { label: '四月龄', id: 1 },
                ],
                contents: [],
                loading: false,
                downloadUrl: '',
                createTime: '',
                pickerOptions:{
                    disabledDate: function(time) {
                         var curDate = new Date(that.createTime).getTime() - 24 * 3600 * 1000
                         let afterDate = new Date('2022/01/01').getTime()
                         // 这里算出一个月的毫秒数,这里使用30的平均值,实际中应根据具体的每个月有多少天计算
                         return time.getTime() < afterDate
                    },
                    shortcuts: [
                        {
                            text: '最近一周',
                            onClick: function (picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                                picker.$emit('pick', [start, end]);
                            }
                        },
                        {
                            text: '最近一个月',
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                                picker.$emit('pick', [start, end]);
                            }
                        },
                        {
                            text: '最近三个月',
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                                picker.$emit('pick', [start, end]);
                            }
                        },
                        {
                            text: '最近半年',
                            onClick(picker) {
                                const end = new Date();
                                const start = new Date();
                                start.setTime(start.getTime() - 3600 * 1000 * 24 * 180);
                                picker.$emit('pick', [start, end]);
                            }
                        },
                    ]
                }
            }
        },
        created: function () {
            this.getQueueList()
        },
        watch: {
            'queue'() {
                this.date = []
                // this.getStartTime()
            },
            'date' (val) {
                if (!this.queue) return this.$message.error('请先选择队列名')
            }
        },
        methods: {
            /**
             * 获取需导出的患者队列 
             */
            getQueueList: function () {
                var that = this
                $bb.ajax({
                    url: URL + 'followup/service/queue/followQueueListQuery',
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({ data: {} }),
                    success: function (res) {
                        if (!res.success) that.$message.error('请求错误，请重新尝试!!!')
                        that.queueList = res.data.rows.filter(function (item) {
                            return item.queueName != '临时门诊队列'
                        });
                    }
                })
            },
            /**
             * 获取开始时间
             */
            getStartTime: function () {
                var that = this
                
                $bb.ajax({
                    url: URL + 'distreat/export/create_time?queue_id=' + this.queue,
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    success: function (res) {
                        if (!res.success) that.$message.error('请求错误，请重新尝试!!!')
                        that.createTime = res.data
                        that.setTime()
                    }
                })
            },
            /**
             * 下一步
             */
            handleNext: function () {
                if (this.step.index == 1 && !this.queue) return this.$message.error('请选择队列');
                if (!this.date[0] || !this.date[1]) return this.$message.error('请选择时间');
                this.step.index++
                // if (this.step.index == 1) return this.getRows()
                if (this.step.index == 3) return this.sendReportRequest()
                // this.step.index++
            },
            /**
             * 上一步
             */
            handlePrev: function () {
                this.step.index--
            },
            /**
             * 查询时间段内是否有条数
             */
            getRows: function () {
                var that = this
                $bb.ajax({
                    url: URL + 'distreat/export/rows_number?queue_id=' + this.queue + '&start_day=' + this.getFormatDate(this.date[0]) + '&end_day=' + this.getFormatDate(this.date[1]),
                    dataType: 'json',
                    contentType: "application/json; charset=utf-8",
                    success: function (res) {
                        if (!res.success) that.$message.error('请求错误，请重新尝试!!!')
                        if (res.data !== 0) {
                            that.step.index++
                        } else {
                            that.$message.error('该时间段内没有数据')
                        }
                    }
                })
            },
            /**
             * 发送导出请求
             */
             sendReportRequest: function () {
                var that = this;
                this.loading = true;
                var param = {
                    queueId: this.queue,
                    startDate: this.getFormatDate(this.date[0]),
                    endDate: this.getFormatDate(this.date[1])
                }
                $bb.ajax({
                    url: URL + '/followup/export/start',
                    dataType: 'json',
                    data: JSON.stringify({
                        data: param
                    }),
                    contentType: "application/json; charset=utf-8",
                    success: function (res) {
                        that.loading = false;
                        console.log(res)
                        that.step.index++
                    }
                })

            },
            /**
             * 序列化参数
             * @param { object } 
             */
            getParams: function (params) {
                var result = ''
                Object.keys(params).forEach(function (key) {
                    result += key + '=' + encodeURIComponent(params[key]) + '&'
                })
                result = result.substring(0, result.length - 1)
                return result
            },
            /**
             * 点击下载导出的文件
             */
            handleDownLoad: function () {
                $bb.openPage('dataExportHistory');
                // var a = document.createElement('a')
                // a.setAttribute('href', 'http://' + location.host +  this.downloadUrl + '?sessionId=' + sessionStorage.getItem('sessionId'))
                // a.setAttribute('download', this.getQueueName() + '-' + new Date().getTime())
                // a.click()
            },
            getTenantId: function (data) {
                return data.apps[0].tenantId
            },
            getQueueName: function() {
                var result = ''
                this.queueList.forEach(q => {
                    if (q.id == this.queue) {
                        result = q.queueIntro
                    }
                })
                return result
            },
            getFormatDate: function (date) {
                var year = date.getFullYear()
                var month = date.getMonth() + 1
                var day = date.getDate()
                function addZore(num) { return num < 10 ? '0' + num : num }
                return year + '-' + addZore(month) + '-' + addZore(day)
            },
            /**
             * 将时间写入到控件中
             */
            setTime: function () {
                var endTime = new Date()
                var startTime = new Date((new Date().getTime() - 6 * 30 * 24 * 3600 * 1000))
                this.date = [ startTime, endTime ]
                this.dateCopy = [ startTime, endTime ]
            },
            /**
             * 改变时间后检测是否大于半年
             */
            handleChangeDate: function (val) {
                var startTime = new Date(val[0]).getTime() / 1000 / 3600 / 24
                var endTime = new Date(val[1]).getTime() / 1000 / 3600 / 24
                if (endTime - startTime > 185) {
                    this.$alert('最多一次性只能导出185天数据', '提示', {
                        confirmButtonText: '确定',
                        callback: () => {
                            this.date = JSON.parse(JSON.stringify(this.dateCopy))
                        }
                    })
                } else {
                    this.dateCopy = JSON.parse(JSON.stringify(this.date))
                }
            }
        }
    })
})